package com.xie.smfs.item;

import com.xie.smfs.damage.ModDamageSources;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.world.World;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import java.util.List;

public class GhostScissorsItem extends Item {
    public GhostScissorsItem(Settings settings) {
        super(settings);
    }

    @Override
    public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
        if (!world.isClient && user instanceof ServerPlayerEntity) {
            ServerPlayerEntity serverPlayer = (ServerPlayerEntity) user;
            ItemStack mainHand = serverPlayer.getMainHandStack();
            ItemStack offHand = serverPlayer.getOffHandStack();
            ItemStack photoStack = ItemStack.EMPTY;

            // 检查哪只手持有照片
            if (PhotoItem.isNamedPhoto(mainHand) && hand == Hand.MAIN_HAND) {
                photoStack = mainHand;
            } else if (PhotoItem.isNamedPhoto(offHand) && hand == Hand.OFF_HAND) {
                photoStack = offHand;
            } else if (PhotoItem.isNamedPhoto(offHand)) {
                photoStack = offHand;
            } else if (PhotoItem.isNamedPhoto(mainHand)) {
                photoStack = mainHand;
            }

            if (!photoStack.isEmpty()) {
                String targetName = photoStack.getName().getString();
                ServerPlayerEntity targetPlayer = world.getServer().getPlayerManager().getPlayer(targetName);

                if (targetPlayer != null && !targetPlayer.isDead()) {
                    // 造成灵异伤害
                    targetPlayer.damage(ModDamageSources.ghost(world), Float.MAX_VALUE);
                    targetPlayer.sendMessage(Text.translatable("message.smfs.photo_killed"), true);
                    serverPlayer.sendMessage(Text.translatable("message.smfs.photo_kill_success"), true);

                    // 播放音效
                    world.playSound(null, serverPlayer.getX(), serverPlayer.getY(), serverPlayer.getZ(),
                            SoundEvents.ENTITY_ILLUSIONER_CAST_SPELL, SoundCategory.PLAYERS, 1.0F, 1.0F);

                    // 损毁照片
                    photoStack.decrement(1);
                    return TypedActionResult.success(user.getStackInHand(hand));
                } else {
                    serverPlayer.sendMessage(Text.translatable("message.smfs.photo_target_not_found"), true);
                }
            } else {
                serverPlayer.sendMessage(Text.translatable("message.smfs.photo_required"), true);
            }
        }
        return TypedActionResult.pass(user.getStackInHand(hand));
    }
}